/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package wh.server;

import java.io.IOException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import wh.Player;
import wh.server.util.Parser;

/**
 *
 * @author Dave
 */
public class Server extends Thread {
    ServerSocket serveSock;
    HashMap tables = new HashMap();
    static final int MAX_CONN_LOBBY = 100;
    static final int SERVER_TIMEOUT = 1000;
    static final int LOBBY_TABLE = 1;
    boolean running = false;

		public static void main(String[] args) {
			try {
				Server server = new Server(5555);
				server.start();
			} catch (IOException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

    public Server(int sock) throws IOException {
        System.out.println("Server being created on port: " + sock);
        serveSock = new ServerSocket(sock);
        serveSock.setSoTimeout(SERVER_TIMEOUT);
        Parser.parseFile(DataStruct.opcodeFunction);
	for(Integer i : DataStruct.opcodeFunction.keySet()) {
            System.out.println("Opcode: " + i.toString() + "\n\tFunction: " + DataStruct.opcodeFunction.get(i).toString());
	}
        tables.put(LOBBY_TABLE, new Table(DataStruct.opcodeFunction, MAX_CONN_LOBBY));
        ((Table)tables.get(LOBBY_TABLE)).start();
    }

    @Override
    public void run() {
        running = true;
        System.out.println("Accepting Clients");
        while(running) {
            try {
                Socket s = serveSock.accept();
		System.out.println("Client accepted: " + s.toString());
                if(((Table)tables.get(LOBBY_TABLE)).addPlayer(new Player(s)) == 0) {
                    s.close();
                }
            } catch (IOException ex) {
                //Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    //super.run();

    public boolean stopServer() {
        running = false;
        return running;
    }
}
